//
//  CheckViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/9/3.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import SVProgressHUD
import RxSwift
import RxCocoa
//import TBScanCodePsrInfosRequest
//import TBSc

class CheckViewController: BaseUIViewController {

    var locationUnit: LocationUnit?
    let codeInputView = CodeInputView()
    let keyboardViewModel = KeyboardViewModel()
    
    let dataArray = BehaviorRelay<[BarcodeInfoModel]>.init(value: [])
    
    let imageView = UIImageView()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupView()
        
        keyboardViewModel.keyboardHeightChange
            .subscribe(onNext: { [weak self] (height, _) in
                guard let self = self else { return }
                self.imageView.snp.updateConstraints { (make) in
                    make.top.equalTo(10 - height)
                }
                self.view.layoutIfNeeded()
            }).disposed(by: rx.disposeBag)
    }
    
    func setupView() {
        self.view.backgroundColor = .white
        self.navigationItem.title = "江苏新源".localized
        
        imageView.config
            .contentMode(.scaleToFill)
            .addTo(view)
            .makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(10)
                make.height.equalTo(SCREEN_WIDTH * 0.693)
        }
        
        let tipLabel = UILabel().config
            .text("请将手机摄像头对准条形码".localized)
            .numberOfLines(0)
            .textAlignment(.center)
            .font(UIFont.systemFont(ofSize: 16, weight: .medium))
            .textColor(APPConfig.baseColor)
            .addTo(view)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(imageView.snp.bottom)
                make.left.equalTo(20)
        }.view
        
        let checkBUtton = UIButton().config
            .backgroundImage(UIImage.imageWithColor(APPConfig.baseColor))
            .title("扫描条码".localized)
            .cornerRadius(22)
            .clipsToBounds(true)
            .titleColor(.white)
            .addTarget(self, action: #selector(scan))
            .addTo(view)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.width.equalTo(220)
                make.height.equalTo(44)
                make.top.equalTo(tipLabel.snp.bottom).offset(50)
        }.view
        
        let sepator = UIView().config
            .backgroundColor(#colorLiteral(red: 0.8235294118, green: 0.8235294118, blue: 0.8235294118, alpha: 1))
            .addTo(self.view)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.height.equalTo(1)
                make.left.equalTo(35)
                make.top.equalTo(checkBUtton.snp.bottom).offset(40)
        }.view
        
        UILabel().config
            .backgroundColor(.white)
            .textColor(#colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1))
            .text("OR")
            .textAlignment(.center)
            .font(UIFont.systemFont(ofSize: 16, weight: .medium))
            .addTo(self.view)
            .makeConstraints { (make) in
                make.center.equalTo(sepator.snp.center)
                make.width.equalTo(100)
        }
        
        codeInputView.submitButton.addTarget(self, action: #selector(codeCheck), for: .touchUpInside)
        self.view.addSubview(codeInputView)
        codeInputView.snp.makeConstraints { (make) in
            make.left.equalTo(35)
            make.centerX.equalToSuperview()
            make.height.equalTo(44)
            make.top.equalTo(sepator.snp.bottom).offset(30)
        }
//        codeInputView.textField.text = "AECA72CD251020001"
        /*
         AECA72CD251020001
         AECA72CD251020002
         AECA72CD251020003
         AECA72CD251020004
         AECA72CD251020005
         */
        
         if let path = Bundle.main.path(forResource: "scan.gif", ofType: nil),
             let data = try? Data.init(contentsOf: URL.init(fileURLWithPath: path)) {
             imageView.image = UIImage.sd_tz_animatedGIF(with: data)
         }
        
    }
    
    /// 输入条码后，点击 提交按钮事件
    @objc func codeCheck() {
        guard let code = self.codeInputView.textField.text,
              code.count > 0 else {
            SVProgressHUD.showInfo(withStatus: "手动输入条形码...");
            return;
        }
        
        self.view.endEditing(true)
        locationUnit = LocationUnit()
        locationUnit?.showLoading = true
        locationUnit?.takeOnce = true
        
        locationUnit?.addressRefuseClosure = { [weak self] in
//            self?.checkCode()
            self?.checkCodeContain(code: code, longitude: "", latitude: "", address: "")
            self?.locationUnit = nil
        }
        locationUnit?.addressUpdate = { [weak self] address in
            let longitude = self?.locationUnit?.longitude
            let latitude = self?.locationUnit?.latitude
//            let code = self.codeInputView.textField.text ?? ""
            self?.checkCodeContain(code: code, longitude: longitude, latitude: latitude, address: address)
//            self?.checkCode(longitude: longitude, latitude: latitude, address: address)
            self?.locationUnit = nil
        }
        locationUnit?.settingClosure = { [weak self] in
            self?.locationUnit = nil
        }
        locationUnit?.startLocation()
    }
    
    /**
     判断条形码 是否存在(如果当前输入的条码或者扫描的条码在接口返回的数据中 就不用去nfc芯片识别了  跳过这一步)
     */
    func checkCodeContain(code: String? = nil, longitude: String? = nil, latitude: String? = nil, address: String? = nil) -> Void {
//        SVProgressHUD.show(withStatus: "")
        APPHud.shared.showLoading(text: "")
        let obj = TBScanCodePsrInfosRequest(barcode: code ?? "");
        obj.startWithCompletionBlock { [weak self] (request) in
//            EDSRespondDataEntity
//            EDSRespondDataEntity *respond = request.responseModelObject;
            let rsp: EDSRespondDataEntity = request.responseModelObject as! EDSRespondDataEntity
            let list: [TBScanCodePsrInfoModel] = rsp.data as! [TBScanCodePsrInfoModel];
//            TBScanCodePsrInfoModel
            var has: Bool = false
            for model in list {
                print("code=\(model.barcode)")
                if model.barcode == code  {
                    has = true
                    break
                }
            }
//            SVProgressHUD.dismiss()
            APPHud.shared.dismiss()
            self?.checkCode(longitude: longitude, latitude: latitude, address: address, has: has)
            
        } failure: { [weak self] (request) in
//            print("err")
            APPHud.shared.dismiss()
        }

        
//        https://app.ae-solar.com.cn/photovoltaic/psr-info/tempList  有个接口

    }
    
    
    /// 检查
    /// - Parameters:
    ///   - longitude: 经度
    ///   - latitude: 维度
    ///   - address: 地址
    ///   - has: 是否存在
    func checkCode(longitude: String? = nil, latitude: String? = nil, address: String? = nil, has: Bool) {
        let code = self.codeInputView.textField.text ?? ""
        ApiManager.scanVerify(code, longitude: longitude ?? "", latitude: latitude ?? "", address: address ?? "").request()
        .errorWhenCodeNot200()
        .dataModelMap(CheckModel.self)
        .trackingLoading()
        .subscribe(onNext: { [weak self] (result) in
            if result.result.isSuccess {
                // has 判断条形码 是否存在(如果当前输入的条码或者扫描的条码在接口返回的数据中 就不用去nfc芯片识别了  跳过这一步)
                if has == true {
                    SVProgressHUD.showInfo(withStatus: "校验成功！")
                    self?.navigationController?.pushTo(SuccessViewController(result: result.psrInfo), remove: 0)
                    return
                }
                let vc = NFCScanViewController.init(barcode: code, longitude: longitude, latitude: latitude, address: address)
                self?.navigationController?.pushViewController(vc, animated: true)
            } else {
                let vc = FailureViewController(psrCheckId: result.id, barCode: code, errorMessage: result.checkMsg, errorCode: result.code)
                self?.navigationController?.pushViewController(vc, animated: true)
            }
            }).disposed(by: rx.disposeBag)
    }
    
    
    /// 点击 “扫描条码” 按钮事件
    @objc func scan() {
        self.view.endEditing(true)
        locationUnit = LocationUnit()
        locationUnit?.showLoading = true
        locationUnit?.takeOnce = true
        
        locationUnit?.addressRefuseClosure = { [weak self] in
            self?.openScanCode()
            self?.locationUnit = nil
        }
        locationUnit?.addressUpdate = { [weak self] address in
            let longitude = self?.locationUnit?.longitude
            let latitude = self?.locationUnit?.latitude
            self?.openScanCode(longitude: longitude, latitude: latitude, address: address)
            self?.locationUnit = nil
        }
        locationUnit?.settingClosure = { [weak self] in
            self?.locationUnit = nil
        }
        locationUnit?.startLocation()
    }
    
    /**
     进入扫码页面
     */
    func openScanCode(longitude: String? = nil, latitude: String? = nil, address: String? = nil) {
        let vc = ScanVerifyViewController.init(longitude: longitude, latitude: latitude, address: address)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .baseColor
    }
    
}
